const CartModel = require('../models/cartModel');
const { success, error, notFound } = require('../utils/response');

const CartController = {
  // 获取用户购物车
  getCart: async (req, res) => {
    try {
      const userId = req.user.id;
      const cartItems = await CartModel.getCartByUserId(userId);
      success(res, cartItems);
    } catch (err) {
      console.error(err);
      error(res, '获取购物车失败', 500);
    }
  },
  
  // 添加商品到购物车
  addToCart: async (req, res) => {
    try {
      const userId = req.user.id;
      const { productId, quantity = 1 } = req.body;
      
      if (!productId) {
        return error(res, '商品ID为必填项', 400);
      }
      
      const successAdd = await CartModel.addToCart(userId, productId, quantity);
      
      if (!successAdd) {
        return error(res, '添加到购物车失败', 500);
      }
      
      success(res, null, '商品已添加到购物车');
    } catch (err) {
      console.error(err);
      error(res, '添加到购物车失败', 500);
    }
  },
  
  // 更新购物车商品数量
  updateCartItem: async (req, res) => {
    try {
      const { quantity } = req.body;
      
      if (!quantity || quantity <= 0) {
        return error(res, '数量必须大于0', 400);
      }
      
      const successUpdate = await CartModel.updateCartItem(req.params.id, quantity);
      
      if (!successUpdate) {
        return notFound(res, '购物车项不存在或更新失败');
      }
      
      success(res, null, '购物车商品数量更新成功');
    } catch (err) {
      console.error(err);
      error(res, '更新购物车失败', 500);
    }
  },
  
  // 从购物车移除商品
  removeFromCart: async (req, res) => {
    try {
      const successRemove = await CartModel.removeFromCart(req.params.id);
      
      if (!successRemove) {
        return notFound(res, '购物车项不存在或删除失败');
      }
      
      success(res, null, '商品已从购物车移除');
    } catch (err) {
      console.error(err);
      error(res, '从购物车移除商品失败', 500);
    }
  },
  
  // 清空购物车
  clearCart: async (req, res) => {
    try {
      const userId = req.user.id;
      const successClear = await CartModel.clearCart(userId);
      
      if (!successClear) {
        return error(res, '清空购物车失败', 500);
      }
      
      success(res, null, '购物车已清空');
    } catch (err) {
      console.error(err);
      error(res, '清空购物车失败', 500);
    }
  }
};

module.exports = CartController;